<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑文档 - 协作白板系统</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        .editor-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
        }

        .editor-toolbar {
            height: 60px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 10px 20px;
            display: flex;
            align-items: center;
            gap: 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .editor-toolbar input {
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            color: white;
            padding: 8px 15px;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 500;
            min-width: 300px;
        }

        .editor-toolbar input::placeholder {
            color: rgba(255,255,255,0.7);
        }

        .editor-toolbar input:focus {
            outline: none;
            background: rgba(255,255,255,0.3);
            border-color: rgba(255,255,255,0.5);
        }

        .editor-toolbar .btn {
            color: white;
            border: 1px solid rgba(255,255,255,0.3);
        }

        .editor-toolbar .btn:hover {
            background: rgba(255,255,255,0.2);
            border-color: rgba(255,255,255,0.5);
        }

        .editor-content {
            flex: 1;
            overflow: hidden;
            display: flex;
        }

        .markdown-editor {
            display: flex;
            width: 100%;
            height: 100%;
        }

        .markdown-input {
            flex: 1;
            border: none;
            padding: 30px;
            font-family: 'Courier New', 'Monaco', monospace;
            font-size: 15px;
            line-height: 1.6;
            resize: none;
            outline: none;
            background: #282c34;
            color: #abb2bf;
        }

        .markdown-preview {
            flex: 1;
            border-left: 3px solid #e9ecef;
            padding: 30px;
            overflow-y: auto;
            background: white;
        }

        .markdown-preview h1 {
            border-bottom: 2px solid #e9ecef;
            padding-bottom: 10px;
        }

        .markdown-preview h2 {
            border-bottom: 1px solid #e9ecef;
            padding-bottom: 8px;
            margin-top: 24px;
        }

        .markdown-preview code {
            background: #f4f4f4;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
        }

        .markdown-preview pre {
            background: #282c34;
            color: #abb2bf;
            padding: 16px;
            border-radius: 6px;
            overflow-x: auto;
        }

        .markdown-preview blockquote {
            border-left: 4px solid #667eea;
            padding-left: 16px;
            color: #6c757d;
            margin: 16px 0;
        }

        .canvas-area {
            flex: 1;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }

        .canvas-area i {
            font-size: 80px;
            color: rgba(0,0,0,0.2);
            margin-bottom: 20px;
        }

        .canvas-area h4 {
            color: rgba(0,0,0,0.5);
        }

        .canvas-area p {
            color: rgba(0,0,0,0.4);
        }

        .save-indicator {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 10px 20px;
            background: #28a745;
            color: white;
            border-radius: 20px;
            display: none;
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body>
    <div class="editor-container">
        <div class="editor-toolbar">
            <input type="text" id="docTitle" placeholder="文档标题" />
            <div class="ms-auto d-flex gap-2">
                <span id="autoSaveText" style="font-size: 14px; opacity: 0.8;">自动保存中...</span>
                <button class="btn btn-sm" onclick="saveDocument()">
                    <i class="fas fa-save"></i> 手动保存
                </button>
                <button class="btn btn-sm" onclick="window.location.href='/documents'">
                    <i class="fas fa-times"></i> 关闭
                </button>
            </div>
        </div>

        <div class="editor-content">
            <div class="markdown-editor" id="markdownEditor" style="display: none;">
                <textarea id="markdownInput" class="markdown-input" placeholder="# 欢迎使用Markdown编辑器

## 功能特性

- 实时预览
- 代码高亮
- 自动保存

## 示例代码

```javascript
function hello() {
    console.log('Hello World');
}
```

## 任务列表

- [ ] 待办事项1
- [x] 已完成事项

> 这是一个引用块
"></textarea>
                <div id="markdownPreview" class="markdown-preview"></div>
            </div>

            <div class="canvas-area" id="boardEditor" style="display: none;">
                <i class="fas fa-pencil-ruler"></i>
                <h4>白板编辑器（演示）</h4>
                <p>实际项目中需要集成 Fabric.js 或 Konva.js</p>
                <button class="btn btn-outline-primary mt-3" onclick="alert('白板编辑功能需要集成 Fabric.js 等绘图库')">
                    <i class="fas fa-info-circle"></i> 查看集成说明
                </button>
            </div>

            <div class="canvas-area" id="mindmapEditor" style="display: none;">
                <i class="fas fa-project-diagram"></i>
                <h4>思维导图编辑器（演示）</h4>
                <p>实际项目中需要集成 jsMind 或 MindElixir</p>
                <button class="btn btn-outline-success mt-3" onclick="alert('思维导图功能需要集成专业库，如 jsMind、MindElixir 等')">
                    <i class="fas fa-info-circle"></i> 查看集成说明
                </button>
            </div>
        </div>
    </div>

    <div class="save-indicator" id="saveIndicator">
        <i class="fas fa-check-circle"></i> 已保存
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

    <script th:inline="javascript">
        const documentId = /*[[${documentId}]]*/ 0;
        const API_BASE_URL = '/api';
        
        axios.defaults.baseURL = API_BASE_URL;
        axios.interceptors.request.use(config => {
            const token = localStorage.getItem('token');
            if (token) {
                config.headers.Authorization = `Bearer ${token}`;
            }
            return config;
        });

        axios.interceptors.response.use(
            response => response.data,
            error => {
                if (error.response?.status === 401) {
                    localStorage.clear();
                    window.location.href = '/login';
                }
                return Promise.reject(error);
            }
        );

        let currentDoc = null;
        let autoSaveTimer = null;

        $(document).ready(function() {
            const token = localStorage.getItem('token');
            if (!token || token === 'undefined' || token === 'null') {
                localStorage.clear();
                window.location.href = '/login';
                return;
            }
            
            console.log('文档ID:', documentId);
            loadDocument();

            $('#markdownInput').on('input', function() {
                const content = $(this).val();
                const html = marked.parse(content);
                $('#markdownPreview').html(html);
                
                clearTimeout(autoSaveTimer);
                autoSaveTimer = setTimeout(() => {
                    autoSave();
                }, 3000);
            });
        });

        async function loadDocument() {
            try {
                console.log('开始加载文档, ID:', documentId);
                const res = await axios.get(`/document/${documentId}`);
                console.log('文档加载成功:', res);
                
                currentDoc = res.data || res;
                console.log('当前文档:', currentDoc);
                
                $('#docTitle').val(currentDoc.title);
                
                if (currentDoc.docType === 'NOTE') {
                    console.log('显示Markdown编辑器');
                    $('#markdownEditor').show();
                    const content = currentDoc.content || '# 欢迎使用Markdown编辑器\n\n开始编写您的笔记...\n\n## 支持的功能\n\n- 标题\n- 列表\n- 代码块\n- 引用\n\n```javascript\nconsole.log("Hello World");\n```\n';
                    $('#markdownInput').val(content);
                    const html = marked.parse(content);
                    $('#markdownPreview').html(html);
                } else if (currentDoc.docType === 'BOARD') {
                    console.log('显示白板编辑器');
                    $('#boardEditor').show();
                } else if (currentDoc.docType === 'MINDMAP') {
                    console.log('显示思维导图编辑器');
                    $('#mindmapEditor').show();
                }

                setInterval(() => {
                    autoSave();
                }, 30000);
            } catch (error) {
                console.error('加载文档失败:', error);
                alert('加载文档失败: ' + (error.response?.data?.message || error.message));
                window.location.href = '/documents';
            }
        }

        async function saveDocument() {
            if (!currentDoc) return;

            const title = $('#docTitle').val();
            let content = currentDoc.content;

            if (currentDoc.docType === 'NOTE') {
                content = $('#markdownInput').val();
            }

            try {
                await axios.put(`/document/${documentId}`, {
                    title: title,
                    content: content
                });
                
                showSaveIndicator();
                console.log('保存成功');
            } catch (error) {
                console.error(error);
                alert('保存失败');
            }
        }

        async function autoSave() {
            if (!currentDoc) return;
            
            $('#autoSaveText').text('保存中...');
            
            await saveDocument();
            
            setTimeout(() => {
                $('#autoSaveText').text('已自动保存');
            }, 500);
        }

        function showSaveIndicator() {
            $('#saveIndicator').fadeIn(300);
            setTimeout(() => {
                $('#saveIndicator').fadeOut(300);
            }, 2000);
        }
    </script>
</body>
</html>

